<template>
  <div class="detail" @scroll="onScroll" ref="detail">
    <!-- 顶部导航 -->
    <van-nav-bar   class="detail-nav-bar1" @click-left="onClickLeft" >
      <template #left >
        <van-icon name="arrow-left" />
      </template>
      <template #right >
        <van-popover
          v-model="showPopover"
          trigger="click"
          theme="dark"
          :actions="actions"
          @select="onSelect"
          placement="bottom-end"
        >
          <template #reference>
             <van-icon name="ellipsis" size="18" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
    <van-nav-bar title="商品详情"   class="detail-nav-bar2" @click-left="onClickLeft">
      <template #left >
        <van-icon name="arrow-left" />
      </template>
      <template #right>
        <van-popover
          v-model="showPopover"
          trigger="click"
          theme="dark"
          :actions="actions"
          @select="onSelect"
          placement="bottom-end"
        >
          <template #reference>
             <van-icon name="ellipsis" size="18" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
    <!-- 图片展示 -->
    <div class="det-img">
        <van-swipe @change="onChange" :initial-swipe="index">
        <van-swipe-item v-for="item in imgList" :key="item" @click="imgPreView">
            <van-image
            width="100vw"
            height="3.75rem"
            fit="contain"
            :src="item"
            />
        </van-swipe-item>
        </van-swipe>
        <h2 class="det-price">￥{{pro.price}}</h2>
        <div class="det-sales">
            <p class="det-sales-left">新品</p>
            <p>销量:{{pro.sales}}</p>
        </div>
        <h3>{{pro.proName}}</h3>
    </div>
    <!-- 规格 -->
    <div class="det-sel">
        <van-cell is-link @click="showCart = !showCart">已选择:8+128G</van-cell>
        <van-cell is-link @click="show = !show">地址:{{area}}
            <van-popup v-model="show" position="bottom" :style="{ height: '60%' }" >
                <van-area title="标题" :area-list="areaList" @confirm="setArea" />
            </van-popup>
        </van-cell>
        <van-cell is-link @click="show2 = !show2">服务:包邮
            <van-popup v-model="show2" position="bottom" :style="{ height: '60%' }" />
        </van-cell>
    </div>
    <!-- 详情 -->
    <div class="det-more">
        <div class="det-more-pro">
            <p>商品详情</p>
            <ul>
                <li>
                    <span>商品名称</span>{{pro.proName}}
                </li>
                <li>
                    <span>商品名称</span>{{pro.proName}}
                </li>
                <li>
                    <span>商品名称</span>{{pro.proName}}
                </li>
                <li>
                    <span>商品名称</span>{{pro.proName}}
                </li>
            </ul>
        </div>
        <img src="https://img01.yzcdn.cn/vant/apple-1.jpg" alt="" width="375">
    </div>
    <!-- 商品导航 -->
    <van-goods-action>
    <van-goods-action-icon icon="shop-o" text="店铺"  />
    <van-goods-action-icon icon="cart-o" text="购物车"  @click="$router.push('/cart')" />
    <van-goods-action-icon icon="star-o" text="收藏" color="#ff5000" />
    <van-goods-action-button type="warning" text="加入购物车" @click="showCart = !showCart"/>
    <van-goods-action-button type="danger" text="立即购买" @click="showCart = !showCart"/>
    </van-goods-action>
    <van-sku
        v-model="showCart"
        :sku="sku"
        :goods="goods"
        :goods-id="pro.proId"
        :quota="5"
        :quota-used="0"
        :show-add-cart-btn="false"
        @buy-clicked="buy"
    />
  </div>
</template>
<script>
import { getDetail, addCart } from '@/api/request.js'
import Vue from 'vue'
import { NavBar, Icon, Swipe, SwipeItem, Image as VanImage, GoodsAction, GoodsActionIcon, GoodsActionButton, Popover, ImagePreview, Toast, Popup, Cell, CellGroup, Sku, Area } from 'vant'
Vue.use(NavBar)
Vue.use(Icon)
Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(VanImage)
Vue.use(GoodsAction)
Vue.use(GoodsActionButton)
Vue.use(GoodsActionIcon)
Vue.use(Popover)
Vue.use(Toast)
Vue.use(Popup)
Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(Sku)
Vue.use(Area)
export default ({
  props: ['id'],
  data () {
    return {
      proList: [],
      show: false,
      showCart: false,
      show2: false,
      area: '请选择配送地址',
      imgList: [
        'https://img01.yzcdn.cn/vant/apple-1.jpg',
        'https://img01.yzcdn.cn/vant/apple-2.jpg'
      ],
      pro: {},
      index: 0,
      showPopover: false,
      actions: [{ text: '首页', path: '/home' }, { text: '分类', path: '/kind' }, { text: '商铺' }],
      sku: {},
      goods: {},
      messageConfig: {
        // 图片上传回调，需要返回一个promise，promise正确执行的结果需要是一个图片url
        uploadImg: () => {
          return new Promise((resolve) => {
            setTimeout(() => resolve('https://img01.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg'), 1000)
          })
        },
        // 最大上传体积 (MB)
        uploadMaxSize: 3,
        // placeholder 配置
        placeholderMap: {
          text: 'xxx',
          tel: 'xxx'
        },
        // 初始留言信息
        // 键：留言 name
        // 值：留言内容
        initialMessages: {
          留言: '留言信息'
        }
      },
      areaList: {
        province_list: {
          110000: '北京市',
          310000: '上海市'
        },
        city_list: {
          110100: '',
          310100: ''
        },
        county_list: {
          110101: '东城区',
          110102: '西城区',
          110105: '朝阳区',
          110106: '丰台区',
          110107: '石景山区',
          110108: '海淀区',
          110109: '门头沟区',
          110111: '房山区',
          110112: '通州区',
          110113: '顺义区',
          110114: '昌平区',
          110115: '大兴区',
          110116: '怀柔区',
          110117: '平谷区',
          110118: '密云区',
          110119: '延庆区',
          310101: '黄浦区',
          310104: '徐汇区',
          310105: '长宁区',
          310106: '静安区',
          310107: '普陀区',
          310109: '虹口区',
          310110: '杨浦区',
          310112: '闵行区',
          310113: '宝山区',
          310114: '嘉定区',
          310115: '浦东新区',
          310116: '金山区',
          310117: '松江区',
          310118: '青浦区',
          310120: '奉贤区',
          310151: '崇明区'
        }
      }
    }
  },
  mounted () {
    getDetail({ id: this.id }).then(data => {
      // console.log(data.data.msg)
      const val = data.data.msg
      this.imgList.unshift(val.img)
      this.pro = val
      this.goods = {
        picture: val.img
      }
      this.sku = {
        tree: [
          {
            k: '颜色', // skuKeyName：规格类目名称
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: '1', // skuValueId：规格值 id
                name: '8+500GB', // skuValueName：规格值名称
                imgUrl: val.img, // 规格类目图片，只有第一个规格类目可以定义图片
                previewImgUrl: val.img // 用于预览显示的规格类目图片
              },
              {
                id: '2',
                name: '16+500GB',
                imgUrl: val.img,
                previewImgUrl: val.img
              }
            ],
            largeImageMode: true //  是否展示大图模式
          }
        ],
        list: [
          {
            id: val.proId, // skuId
            s1: '1', // 规格类目 k_s 为 s1 的对应规格值 id
            price: val.price * 100, // 价格（单位分）
            stock_num: val.stock // 当前 sku 组合对应的库存
          },
          {
            id: val.proId, // skuId
            s1: '2', // 规格类目 k_s 为 s1 的对应规格值 id
            price: val.price * 100, // 价格（单位分）
            stock_num: val.stock // 当前 sku 组合对应的库存
          }
        ],
        price: val.price, // 默认价格（单位元）
        stock_num: val.stock, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        hide_stock: false // 是否隐藏剩余库存
      }
    })
  },
  methods: {
    onScroll () {
      document.querySelector('.detail-nav-bar2').style.opacity = this.$refs.detail.scrollTop / 100
    },
    onClickLeft () {
      this.$router.back()
    },
    onSelect (v) {
      this.$router.push(v.path)
    },
    onChange (index) {
      this.index = index
    },
    imgPreView () {
      const that = this
      ImagePreview({
        images: this.imgList,
        startPosition: this.index,
        onChange (index) {
          that.index = index
        }
      })
    },
    buy (v) {
      // console.log(v)
      const that = this
      addCart({
        userId: sessionStorage.getItem('userId'),
        proId: v.goodsId,
        num: v.selectedNum
      }).then(data => {
        // console.log(data)
        if (data.data.code !== 202) {
          Toast('添加购物车成功')
          that.showCart = !that.showCart
        } else {
          Toast('添加购物车失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    setArea (v) {
      let str = '至'
      v.forEach(val => {
        str += val.name
      })
      this.area = str
    }
  }
})
</script>
<style lang="scss" scoped>
.detail{
  background: #efefef;
  overflow: auto;
  padding-bottom:0.6rem;
  .detail-nav-bar1,.detail-nav-bar2{
    position: fixed;
    width: 100vw;
    &::after{
      border-bottom: none;
    }
  }
  .detail-nav-bar1{
    background: none;
    .van-nav-bar__left,.van-nav-bar__right{
      i{
        position:static;
        color: #fff;
        width: 0.2rem;
        height: 0.2rem;
        line-height: 0.2rem;
        border-radius: 50%;
        background: #666;
      }
    }
  }
  .detail-nav-bar2{
    // display: none;
    opacity: 0;
    i{
      color: #666;
      width: 0.2rem;
      height: 0.2rem;
      line-height: 0.2rem;
    }
  }
  .det-img{
    background: #fff;
    padding-bottom: 0.2rem;
    .det-price{
        color: red;
        padding-left:.12rem;
    }
    .det-sales{
        display: flex;
        justify-content: space-between;
        padding: .1rem .2rem .1rem .15rem;
        font-size: .13rem;
        .det-sales-left{
            color: red;
            border:1px red solid;
            border-radius: 0.12rem;
            padding: .02rem .08rem;
        }
    }
    h3{
        padding: 0 0.2rem;
    }
  }
    .det-sel{
        margin-top: 0.15rem;
    }
    .det-more{
        margin-top: 0.15rem;
        background: #fff;
        font-size: .14rem;
        .det-more-pro{
            padding: .1rem .2rem;
            p{
                padding: .1rem 0;
            }
            li{
                padding: .1rem 0;
                border-top: 2px #efefef dotted;
                span{
                    color: #c8c9cc;
                    padding-right: 0.3rem;
                    line-height: .2rem;
                }
            }
        }
    }
}

</style>
